﻿using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using YY.Admin.Core;
using YY.Admin.Core.EventBus;
using YY.Admin.Core.Session;
using YY.Admin.Services;
using YY.Admin.Services.Service.Auth;
using YY.Admin.Services.Service.Menu;
using YY.Admin.Views;
using YY.Admin.Views.SysManage;

namespace YY.Admin.ViewModels
{
    public class MenuItem
    {
        public string Name { get; set; } = string.Empty;
        public string Icon { get; set; } = string.Empty;
        // 图标可以是资源键或路径数据
        public string ViewName { get; set; } = string.Empty;
        public ObservableCollection<MenuItem> Children { get; set; } = [];
    }

    public class MainViewModel : BaseViewModel
    {
        private static readonly Dictionary<string, Type> _viewTypeCache = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
        private readonly ISysAuthService _authService;
        private readonly ISysMenuService _sysMenuService;
        private SysUser? _currentUser;
        private MenuItem? _selectedMenuItem;
        private string _menuLoadingMessage = "加载菜单中...";

        #region 标签集合
        public ObservableCollection<TabItemModel> OpenTabs { get; } = new ObservableCollection<TabItemModel>();
        private TabItemModel _selectedTab;
        public TabItemModel SelectedTab
        {
            get => _selectedTab;
            set
            {
                SetProperty(ref _selectedTab, value);
                if (_selectedTab != null)
                {
                    // 当选中某个标签时，确保该标签内的区域已经加载并导航到指定视图
                    // TabContentView 的 Loaded 会执行 RequestNavigate，一般不需要再次导航。
                }
            }
        }
        // 原来的 NavigateCommand 改为：
        public DelegateCommand<MenuItem> NavigateCommand { get; }
        #endregion
        public MainViewModel(
            ISysAuthService authService, 
            ISysMenuService sysMenuService,
            IContainerExtension _container
            ) :base(_container)
        {
            _authService = authService;
            Title = "后台管理系统";
            _sysMenuService = sysMenuService;
            // 订阅用户变更事件
            _currentUser = _authService.CurrentUser;
            _authService.UserChanged += OnUserChanged;
            LogoutCommand = new DelegateCommand(async () => await LogoutAsync());
            RetryLoadMenuCommand = new DelegateCommand(() => LoadMenuAsync());
            // ...
            NavigateCommand = new DelegateCommand<MenuItem>(menu => OpenOrActivateTab(menu));
            // 清空现有菜单
            MenuItems.Clear();
            // 异步初始化菜单
            LoadMenuAsync();
            // 默认导航到仪表盘（延迟执行）
            ScheduleDefaultNavigation();

            // 主题设置命令
            OpenThemeSettingsCommand = new DelegateCommand(OpenThemeSettings);
            ResetThemeSettingsCommand = new DelegateCommand(ResetThemeSettings);
            ApplyThemeSettingsCommand = new DelegateCommand(ApplyThemeSettings);
            SaveThemeSettingsCommand = new DelegateCommand(SaveThemeSettings);
            // 加载初始主题设置
            LoadThemeSettings();
        }
        #region 主题
        private bool _isSettingsOpen;
        public bool IsSettingsOpen
        {
            get => _isSettingsOpen;
            set => SetProperty(ref _isSettingsOpen, value);
        }

        // 主题设置相关属性
        private SolidColorBrush _headerBrush = Brushes.White;
        public SolidColorBrush HeaderBrush
        {
            get => _headerBrush;
            set => SetProperty(ref _headerBrush, value);
        }

        private SolidColorBrush _menuBrush = (SolidColorBrush)new BrushConverter().ConvertFrom("#001529");
        public SolidColorBrush MenuBrush
        {
            get => _menuBrush;
            set => SetProperty(ref _menuBrush, value);
        }

        private SolidColorBrush _headerBackground = Brushes.White;
        public SolidColorBrush HeaderBackground
        {
            get => _headerBackground;
            set => SetProperty(ref _headerBackground, value);
        }

        private SolidColorBrush _menuBackground = (SolidColorBrush)new BrushConverter().ConvertFrom("#001529");
        public SolidColorBrush MenuBackground
        {
            get => _menuBackground;
            set => SetProperty(ref _menuBackground, value);
        }
        // 主题设置命令
        public ICommand OpenThemeSettingsCommand { get; }
        public ICommand ResetThemeSettingsCommand { get; }
        public ICommand ApplyThemeSettingsCommand { get; }
        public ICommand SaveThemeSettingsCommand { get; }

        #endregion
        public SysUser? CurrentUser
        {
            get => _currentUser;
            set => SetProperty(ref _currentUser, value);
        }

        public ObservableCollection<MenuItem> MenuItems { get; } = [];

        public MenuItem? SelectedMenuItem
        {
            get => _selectedMenuItem;
            set => SetProperty(ref _selectedMenuItem, value);
        }
        public string MenuLoadingMessage
        {
            get => _menuLoadingMessage;
            private set => SetProperty(ref _menuLoadingMessage, value);
        }
 
        public DelegateCommand LogoutCommand { get; }
        public DelegateCommand RetryLoadMenuCommand { get; }
        private void OnUserChanged(object? sender, SysUser? user)
        {
            CurrentUser = user;
            //// 用户变更时刷新菜单
            //LoadMenuAsync();
        }
        /// <summary>
        /// 异步加载菜单【后续使用缓存以及权限管理】
        /// </summary>
        private async void LoadMenuAsync()
        {
            try
            {
                // 异步获取菜单数据
                var menuTree = await _sysMenuService.GetLoginMenuTree();
                // 转换菜单数据
                ConvertMenuTreeToViewModel(menuTree);
                // 添加默认菜单项（如果系统需要）
                AddDefaultMenuItems();
            }
            catch (Exception ex)
            {
                _logger.Error($"菜单加载失败: {ex.Message}", ex);
                MenuLoadingMessage = $"加载失败: {ex.Message}";
                // 显示错误菜单项
                MenuItems.Add(new MenuItem
                {
                    Name = "菜单加载失败",
                    Icon = "ErrorOutline",
                    ViewName = "ErrorView",
                    Children = { new MenuItem { Name = "点击重试", Icon = "Refresh" } }
                });
            }
            finally
            {
               
            }
        }
        /// <summary>
        /// 将服务层菜单树转换为视图模型
        /// </summary>
        private void ConvertMenuTreeToViewModel(List<MenuOutput> menuTree)
        {
            // 过滤并排序菜单项：只包含目录和菜单类型，排除按钮类型，并按排序号排序
            var rootMenus = menuTree
                .Where(m => m.Type == MenuTypeEnum.Dir || m.Type == MenuTypeEnum.Menu)
                .Where(m => m.Status == StatusEnum.Enable) // 只包含启用状态的菜单
                .Where(m => !(m?.IsHide ?? false)) // 排除隐藏的菜单
                .OrderBy(m => m.OrderNo)
                .ToList();
            // 递归转换菜单项
            void ConvertMenu(MenuOutput source, MenuItem target)
            {
                target.Name = source?.Title ?? source.Name;
                target.Icon = ConvertHtmlEntityToUnicode(source?.Icon ?? "&#xe810;");
                target.ViewName = source!.Path; // 根据组件路径获取视图名称

                // 添加子菜单（如果有）
                if (source.Children != null && source.Children.Any())
                {
                    // 过滤并排序子菜单
                    var childMenus = source.Children
                        .Where(c => c.Type == MenuTypeEnum.Menu) // 子菜单只包含菜单类型
                        .Where(c => c.Status == StatusEnum.Enable)
                        .Where(c => !(c?.IsHide ?? false))
                        .OrderBy(c => c.OrderNo)
                        .ToList();

                    foreach (var child in childMenus)
                    {
                        var childItem = new MenuItem();
                        ConvertMenu(child, childItem);
                        target.Children.Add(childItem);
                    }
                }
            }
            // 处理每个根菜单
            foreach (var root in rootMenus)
            {
                var rootItem = new MenuItem();
                ConvertMenu(root, rootItem);

                // 如果根菜单是目录但没有子菜单，则不显示
                if (root.Type == MenuTypeEnum.Dir && !rootItem.Children.Any())
                    continue;

                MenuItems.Add(rootItem);
            }
        }
        /// <summary>
        /// 添加默认菜单项
        /// </summary>
        private void AddDefaultMenuItems()
        {
            // 确保始终有仪表盘菜单
            //bool hasDashboard = false;
            //foreach (var item in MenuItems)
            //{
            //    if (item.ViewName == nameof(DashboardView))
            //    {
            //        hasDashboard = true;
            //        break;
            //    }
            //}

            //if (!hasDashboard)
            //{
            //    MenuItems.Insert(0, new MenuItem
            //    {
            //        Name = "仪表盘",
            //        Icon = "DashboardOutlined",
            //        ViewName = nameof(DashboardView)
            //    });
            //}
        }

        /// <summary>
        /// 打开或激活一个标签页（若已打开则激活，否则新建）
        /// </summary>
        private void OpenOrActivateTab(MenuItem menuItem)
        {
            if (menuItem == null || string.IsNullOrEmpty(menuItem.ViewName))
                return;

            var existing = OpenTabs.FirstOrDefault(t => string.Equals(t.ViewName, menuItem.ViewName, StringComparison.OrdinalIgnoreCase));
            if (existing != null)
            {
                // 延迟设置选中，防止 UI 尚未生成内容
                System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    SelectedTab = existing;
                }), DispatcherPriority.Background);
                return;
            }

            var tab = new TabItemModel
            {
                Header = menuItem.Name,
                Icon = menuItem.Icon,
                ViewName = menuItem.ViewName
            };

            tab.CloseCommand = new DelegateCommand(() => CloseTab(tab));

            OpenTabs.Add(tab);

            // 延迟设置选中项，等待模板生成并触发 TabContentView.Loaded
            System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                SelectedTab = tab;
            }), DispatcherPriority.Background);
        }

        /// <summary>
        /// 关闭标签并清理对应 Prism 区域
        /// </summary>
        private void CloseTab(TabItemModel tab)
        {
            if (tab == null) return;

            try
            {
                // 先从 RegionManager 中移除该区域的内容
                if (_regionManager.Regions.ContainsRegionWithName(tab.Id))
                {
                    var region = _regionManager.Regions[tab.Id];
                    region.RemoveAll();
                    _regionManager.Regions.Remove(tab.Id);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"关闭标签移除 Region 出错: {ex.Message}");
                _logger?.Error($"关闭标签移除 Region 出错: {ex.Message}", ex);
            }

            // 然后从集合中移除
            var idx = OpenTabs.IndexOf(tab);
            OpenTabs.Remove(tab);

            // 如果被选中的标签被关闭，尝试选中邻近的标签
            if (SelectedTab == tab)
            {
                if (OpenTabs.Any())
                {
                    var newIndex = Math.Min(idx, OpenTabs.Count - 1);
                    SelectedTab = OpenTabs[newIndex];
                }
                else
                {
                    SelectedTab = null;
                    // 如果需要，可以导航回默认 Dashboard
                    // RequestNavigate("ContentRegion", nameof(DashboardView));
                }
            }
        }

        /// <summary>
        /// 安排默认导航
        /// </summary>
        private void ScheduleDefaultNavigation()
        {
            System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                try
                {
                    // 改为打开仪表盘标签而不是请求 ContentRegion
                    // 假设你注册菜单或知道 Dashboard 的 ViewName 为 "DashboardView"
                    //var fakeMenu = new MenuItem { Name = "仪表盘", ViewName = nameof(DashboardView), Icon = "&#xe8b8;" };
                    var fakeMenu = new MenuItem { Name = "仪表盘", ViewName = nameof(DashboardView), Icon = ConvertHtmlEntityToUnicode("&#xe801;") };
                    OpenOrActivateTab(fakeMenu);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"默认导航失败: {ex.Message}");
                    _logger.Error($"默认导航失败: {ex.Message}", ex);
                }
            }), DispatcherPriority.ApplicationIdle);
        }
        /// <summary>
        ///导航跳转
        /// </summary>
        /// <param name="menuItem"></param>
        private void Navigate(MenuItem? menuItem)
        {
            if (menuItem == null || string.IsNullOrEmpty(menuItem.ViewName))
                return;

            try
            {
                Debug.WriteLine($"尝试导航到: {menuItem.ViewName}");

                // 检查视图是否存在
                var viewType = GetViewTypeByName(menuItem.ViewName);
                if (viewType == null)
                {
                    Debug.WriteLine($"视图 '{menuItem.ViewName}' 不存在");
                    NavigateToNotFound(menuItem.ViewName);
                    return;
                }

                // 更新选中的菜单项
                SelectedMenuItem = menuItem;

                // 执行导航
                Debug.WriteLine($"导航到: {menuItem.ViewName}");
                RequestNavigate("ContentRegion", menuItem.ViewName);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"导航错误: {ex.Message}");
                NavigateToNotFound(menuItem.ViewName, ex.Message);
            }
        }
        private Type GetViewTypeByName(string viewName)
        {
            // 检查缓存
            if (_viewTypeCache.TryGetValue(viewName, out var cachedType))
                return cachedType;

            // 获取应用程序中的所有程序集
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            // 查找匹配的视图类型
            foreach (var assembly in assemblies)
            {
                try
                {
                    // 尝试在程序集中查找匹配的类型
                    var types = assembly.GetTypes();
                    var viewType = types.FirstOrDefault(t =>
                        t.Name.Equals(viewName, StringComparison.OrdinalIgnoreCase) &&
                        typeof(FrameworkElement).IsAssignableFrom(t));

                    if (viewType != null)
                    {
                        // 添加到缓存
                        _viewTypeCache[viewName] = viewType;
                        return viewType;
                    }
                }
                catch (ReflectionTypeLoadException)
                {
                    // 忽略无法加载类型的程序集
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"扫描程序集 {assembly.FullName} 时出错: {ex.Message}");
                }
            }

            // 缓存未找到的结果
            _viewTypeCache[viewName] = null;
            return null;
        }
        private void NavigateToNotFound(string requestedView, string error = null)
        {
            // 创建导航参数
            var parameters = new NavigationParameters();
            if (!string.IsNullOrEmpty(requestedView))
                parameters.Add("RequestedView", requestedView);

            if (!string.IsNullOrEmpty(error))
                parameters.Add("ErrorMessage", error);

            // 导航到404页面
            SafeNavigate("ContentRegion", "NotFoundView", parameters);

            // 重置菜单选择
            SelectedMenuItem = null;
        }
        private async Task LogoutAsync()
        {
            await _authService.LogoutAsync();

            // 返回登录窗口
            System.Windows.Application.Current.MainWindow?.Hide();
            var loginWindow = new LoginWindow();
            System.Windows.Application.Current.MainWindow = loginWindow;
            loginWindow.Show();
        }
        private string ConvertHtmlEntityToUnicode(string htmlEntity)
        {
            if (string.IsNullOrEmpty(htmlEntity))
                return "\ue7c6"; // 默认图标

            if (htmlEntity.StartsWith("&#x") && htmlEntity.EndsWith(";"))
            {
                string hexCode = htmlEntity.Substring(3, htmlEntity.Length - 4);
                if (int.TryParse(hexCode, NumberStyles.HexNumber, null, out int unicodeValue))
                {
                    return char.ConvertFromUtf32(unicodeValue);
                }
            }
            return htmlEntity;
        }
        #region 主题
        private void OpenThemeSettings()
        {
            // 加载当前应用到预览区
            HeaderBrush = HeaderBackground;
            MenuBrush = MenuBackground;
            IsSettingsOpen = true;
        }

        private void ResetThemeSettings()
        {
            // 重置为默认值
            HeaderBrush = Brushes.White;
            MenuBrush = (SolidColorBrush)new BrushConverter().ConvertFrom("#001529");
        }

        private void ApplyThemeSettings()
        {
            // 应用预览效果
            HeaderBackground = HeaderBrush;
            MenuBackground = MenuBrush;
        }

        private void SaveThemeSettings()
        {
            try
            {
                var settings = new ThemeSettings
                {
                    HeaderBackground = HeaderBrush.Color.ToString(),
                    MenuBackground = MenuBrush.Color.ToString()
                };

                // 保存到文件
                var json = JsonConvert.SerializeObject(settings, Formatting.Indented);
                var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "themeSettings.json");
                File.WriteAllText(filePath, json);

                // 关闭设置面板
                IsSettingsOpen = false;

                // 应用最终设置
                ApplyThemeSettings();
                //通知主题变更
                _eventAggregator.GetEvent<ThemeChangedEvent>().Publish(settings);
            }
            catch (Exception ex)
            {
                _logger.Error($"保存主题设置失败: {ex.Message}", ex);
            }
        }

        private void LoadThemeSettings()
        {
            try
            {
                var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "themeSettings.json");
                if (File.Exists(filePath))
                {
                    var json = File.ReadAllText(filePath);
                    var settings = JsonConvert.DeserializeObject<ThemeSettings>(json);

                    if (!string.IsNullOrEmpty(settings.HeaderBackground))
                    {
                        HeaderBackground = new SolidColorBrush(
                            (Color)ColorConverter.ConvertFromString(settings.HeaderBackground));
                    }

                    if (!string.IsNullOrEmpty(settings.MenuBackground))
                    {
                        MenuBackground = new SolidColorBrush(
                            (Color)ColorConverter.ConvertFromString(settings.MenuBackground));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"加载主题设置失败: {ex.Message}", ex);
            }
        }
        #endregion

    }
}
